<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { validatePassword, validateEmail } from "@/utils/validate";
import Sidentify from "@/components/Sidentify.vue";
import { encryptData } from "@/utils/index";
import { loginApi } from "@/api/user";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/user";
const router = useRouter();
const userStore = useUserStore();

const formRef = ref();
const form = reactive({
  email: "",
  sidentifyMode: "",
  password: "",
});
const rules = {
  email: [{ validator: validateEmail, trigger: "blur" }],
  sidentifyMode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }],
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (!contrastSidentify()) return;
      // 加密密码
      // const data = {
      //   email: form.email,
      //   password: encryptData(form.password),
      // };
      const res = await loginApi(form);
      if (res.data.status === 200) {
        ElMessage({ type: "success", message: "登录成功" });
        sessionStorage.setItem("token", res.data.data.token);
        sessionStorage.setItem("userInfo", JSON.stringify(res.data.data));
        userStore.setIsLogin(true);
        userStore.setUserInfo(res.data.data);
        router.replace({ path: "/home" });
      } else {
        ElMessage({ type: "error", message: res.data.message });
      }
    }
  });
};

const identifyCodes = ref("23456789abcdefghjkmnpqrstuvwxyz"); //验证码出现的数字和字母
let identifyCode = ref(""); //图形验证码

//组件挂载
onMounted(() => {
  identifyCode.value = "";
  makeCode(identifyCodes.value, 4);
});

// 生成随机数
const randomNum = (min, max) => {
  max = max + 1;
  return Math.floor(Math.random() * (max - min) + min);
};
// 随机生成验证码字符串
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length - 1)];
  }
};
// 更新验证码
const refreshCode = () => {
  identifyCode.value = "";
  makeCode(identifyCodes.value, 4);
};
const contrastSidentify = () => {
  if (!form.sidentifyMode) {
    ElMessage({ type: "error", message: "验证码不能为空！" });
    return false;
  }
  //验证验证码是否正确
  if (form.sidentifyMode != identifyCode.value) {
    ElMessage({ type: "error", message: "验证码错误" });
    refreshCode();
    return false;
  }
  return true;
};
</script>
<template>
  <div class="page-container">
    <div class="card shadow-sm border-0">
      <div class="d-flex align-items-center text-center">
        <div class="card-body">
          <h4 class="mb-4 h5">
            <span class="text-primary alert-link">登录</span> ·
            <RouterLink class="c-pointer text-black-50" to="/register"
              >注册</RouterLink
            >
          </h4>
          <el-form :model="form" ref="formRef" :rules="rules">
            <el-form-item prop="email">
              <el-input
                type="text"
                v-model="form.email"
                clearable
                placeholder="请输入邮箱"
                auto-complete="off"
              />
            </el-form-item>
            <el-form-item prop="sidentifyMode" class="code">
              <el-input
                type="text"
                placeholder="请输入验证码"
                v-model="form.sidentifyMode"
                clearable
                @change="contrastSidentify"
                auto-complete="off"
              />
              <div @click="refreshCode">
                <Sidentify :identifyCode="identifyCode" />
              </div>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                v-model="form.password"
                clearable
                placeholder="请输入密码"
                auto-complete="off"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                round
                class="btn-block"
                @click="submitForm(formRef)"
              >
                登录
              </el-button>
              <div class="mt-2 text-black-50 small w-100">
                忘记密码？
                <RouterLink class="text-secondary c-pointer" to="/retrieve">
                  找回密码
                </RouterLink>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.card {
  width: 350px;
  min-height: 100px;
  margin: 4rem auto 0;
}
.code {
  :deep(.el-form-item__content) {
    flex-wrap: nowrap;
  }
}
</style>
